import { Catch, ArgumentsHost, BadRequestException } from '@nestjs/common';
import { GqlExceptionFilter } from '@nestjs/graphql';
import { UserInputError } from 'apollo-server';

@Catch(BadRequestException)
export class BadRequestExceptionFilter implements GqlExceptionFilter {
  catch(exception: BadRequestException, host: ArgumentsHost) {
    const message = exception.message.message;
    if (message && message.length > 0) {
      // wrap class validator error
      const constraints = message[0].constraints;
      const finalMsg = constraints
        ? constraints[Object.keys(constraints)[0]]
        : '参数错误！';
      const property = message[0].property;
      return new UserInputError(finalMsg, { property });
    } else {
      return exception;
    }
  }
}
